<template>
  <el-container>
    <el-header>
      <el-button type="primary" @click="handleAddBuilding">添加楼栋<i class="el-icon-circle-plus-outline"></i></el-button>
      <el-button type="primary" @click="handleAddUnit">添加单元<i class="el-icon-circle-plus-outline"></i> </el-button>
      <el-button type="primary" @click="handleAddRoom">添加房屋<i class="el-icon-circle-plus-outline"></i> </el-button>
      <el-button type="primary" @click="handleClickDelete">删除楼栋<i class="el-icon-remove-outline"></i></el-button>
      <el-button type="primary" @click="getRooms(1)">查询所有的房屋<i class=""></i></el-button>
    </el-header>
    <el-container>
      <el-aside width="100px">
        <el-tree
            :data="buildingList"
            node-key="id"
            :props="{ label: 'label', children: 'children' }"
            @node-click="handleChooseBuilding"
        ></el-tree>
      </el-aside>
      <el-main>
        <el-table
            :data="pageInfo.list"
            border
            style="width: 100%"
            v-loading="loading">
          <el-table-column
              prop="building.buildingName"
              label="楼栋"
              width="150">
          </el-table-column>
          <el-table-column
              prop="unit.unitName"
              label="单元"
              width="120">
          </el-table-column>
          <el-table-column
              prop="floor"
              label="层数"
              width="120">
          </el-table-column>
          <el-table-column
              prop="roomName"
              label="房间名"
              width="120">
          </el-table-column>
          <el-table-column
              prop="owner.userName"
              label="业主"
              width="120">
          </el-table-column>
          <el-table-column
              prop="grossArea"
              label="建筑面积(㎡)"
              width="120">
          </el-table-column>
          <el-table-column
              prop="usableArea"
              label="室内面积(㎡)"
              width="120">
          </el-table-column>
          <el-table-column
              prop="price"
              label="物业费单价(元/㎡)"
              width="180" >
          </el-table-column>
          <el-table-column
              prop="message"
              label="户型"
              width="120" >
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="120">
            <template slot-scope="scope">
              <el-button
                  type="text"
                  size="small"
                  @click="handleUpdate(scope.row)">
                修改
              </el-button>
              <el-button
                  type="text"
                  size="small"
                  @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next"
            @current-change="handlePageNumChange"
            :current-page="pageInfo.pageNum"
            :page-size="pageInfo.pageSize"
            :total="pageInfo.total">
        </el-pagination>
      </el-main>
    </el-container>
    <el-dialog title="添加楼栋" :visible.sync="dialogFormVisible">
      <el-form :model="building" :rules="rules" ref="buildingForm" label-width="120px">
        <el-form-item label="楼栋名" prop="buildingName">
          <el-input v-model="building.buildingName" placeholder="请输入楼栋名字"></el-input>
        </el-form-item>
        <el-form-item>
          <span>楼栋名的格式：*栋,请不要随便填写</span>
        </el-form-item>
        <el-form-item label="对这栋楼的说明" prop="remark">
          <el-input
              v-model="building.remark"
              resize="none"
              type="textarea">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleBuildingRemove">取 消</el-button>
        <el-button type="primary" :plain="true" @click="handleBuildingSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加单元" :visible.sync="showUnit">
      <el-form :model="unit" :rules="rules" ref="unitForm" label-width="100px">
        <el-form-item label="楼栋名" prop="buildingId">
          <el-select
              v-model="unit.buildingId"
              placeholder="请选择楼栋"
              :disabled="true">
            <el-option
                v-for="building in buildingList"
                :key="building.id"
                :label="building.label"
                :value="building.id"
            ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="单元名" prop="unitName">
          <el-input v-model="unit.unitName" placeholder="请输入单元名字"></el-input>
        </el-form-item>
        <el-form-item>
          <span>单元名的格式：*单元,请不要随便填写</span>
        </el-form-item>
        <el-form-item label="层数" prop="floor">
          <el-input v-model.number="unit.floor" placeholder="请输入该单元的层数"></el-input>
        </el-form-item>
        <el-form-item label="有无电梯" prop="elevator">
          <el-radio-group v-model="unit.elevator">
            <el-radio :label="true">有电梯</el-radio>
            <el-radio :label="false">无电梯</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleUnitRemove">取 消</el-button>
        <el-button type="primary" :plain="true" @click="handleUnitSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加房屋" :visible.sync="showRoom">
      <el-form :model="room" :rules="rules" ref="roomForm" label-width="100px" class="custom-form">
        <div class="form-row">
          <el-form-item label="楼栋" prop="buildingId">
            <el-select v-model="room.buildingId" placeholder="请选择楼栋" clearable @change="ChangeBuilding" v-if="buildingList.length > 0">
              <el-option
                  v-for="building in buildingList"
                  :key="building.id"
                  :label="building.label"
                  :value="building.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="单元" prop="unitId">
            <el-select v-model="room.unitId" placeholder="请选择单元" clearable @change="ChangeUnit" v-if="unitList.length > 0">
              <el-option
                  v-for="unit in unitList"
                  :key="unit.id"
                  :label="unit.unitName"
                  :value="unit.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="单元楼层" prop="floor" class="form-item">
            <el-input
                v-model.number="room.floor"
            :disabled="true"
            placeholder="请输入楼层"
            ></el-input>
          </el-form-item>
          <el-form-item label="房间名" prop="roomName" class="form-item">
            <el-input v-model="room.roomName" placeholder="请输入房间名" clearable></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="建筑面积(㎡)" prop="grossArea" class="form-item">
            <el-input v-model="room.grossArea" placeholder="请输入房间的建筑面积" clearable></el-input>
          </el-form-item>
          <el-form-item label="室内面积(㎡)" prop="usableArea" class="form-item">
            <el-input v-model="room.usableArea" placeholder="请输入房间的室内面积" clearable></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="物业费单价(元/㎡)" prop="price" class="form-item">
            <el-input v-model="room.price" placeholder="请输入该房间的物业费单价" clearable></el-input>
          </el-form-item>
          <el-form-item label="房屋的状态" prop="type" class="form-item">
            <el-select v-model="room.type" placeholder="请选择房屋的状态" clearable>
              <el-option
                  key="员工宿舍"
                  label="员工宿舍"
                  value="员工宿舍"
              ></el-option>
              <el-option
                  key="商用"
                  label="商用"
                  value="商用"
              ></el-option>
              <el-option
                  key="住宅"
                  label="住宅"
                  value="住宅"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="户型" prop="message" class="full-width-item">
            <el-input v-model="room.message" placeholder="请输入该房间的户型" clearable></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleRoomRemove">取 消</el-button>
        <el-button type="primary" :plain="true" @click="handleRoomSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改房屋" :visible.sync="showEdit">
      <el-form :model="room" :rules="rules" ref="roomEditForm" label-width="100px" class="custom-form">
        <div class="form-row">
          <el-form-item label="楼栋" prop="buildingId" class="form-item">
            <el-select v-model="room.buildingId" placeholder="请选择楼栋" @change="ChangeBuilding">
              <el-option
                  v-for="building in buildingList"
                  :key="building.id"
                  :label="building.label"
                  :value="Number(building.id)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单元" prop="unitId" class="form-item">
            <el-select v-model="room.unitId" placeholder="请选择单元">
              <el-option
                  v-for="unit in unitList"
                  :key="unit.id"
                  :label="unit.unitName"
                  :value="Number(unit.id)"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="单元楼层" class="form-item">
            <el-input
                v-model.number="room.floor"
                placeholder="请输入楼层"
            ></el-input>
          </el-form-item>
          <el-form-item label="房间名" prop="roomName" class="form-item">
            <el-input v-model="room.roomName" placeholder="请输入房间名" clearable></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="建筑面积(㎡)" prop="grossArea" class="form-item">
            <el-input v-model="room.grossArea" placeholder="请输入房间的建筑面积" clearable></el-input>
          </el-form-item>
          <el-form-item label="室内面积(㎡)" prop="usableArea" class="form-item">
            <el-input v-model="room.usableArea" placeholder="请输入房间的室内面积" clearable></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="物业费单价(元/㎡)" prop="price" class="form-item">
            <el-input v-model="room.price" placeholder="请输入该房间的物业费单价" clearable></el-input>
          </el-form-item>
          <el-form-item label="房屋的状态" prop="type" class="form-item">
            <el-select v-model="room.type" placeholder="请选择房屋的状态" clearable>
              <el-option
                  key="员工宿舍"
                  label="员工宿舍"
                  value="员工宿舍"
              ></el-option>
              <el-option
                  key="商用"
                  label="商用"
                  value="商用"
              ></el-option>
              <el-option
                  key="住宅"
                  label="住宅"
                  value="住宅"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="户型" prop="message" class="full-width-item">
            <el-input v-model="room.message" placeholder="请输入该房间的户型" clearable></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleRoomEditRemove">取 消</el-button>
        <el-button type="primary" :plain="true" @click="handleRoomEditSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import index from "vuex";

export default {
  name: "BuildingListView",
  data() {
    return {
      showEdit: false,
      loading: false,
      searchRoom:{
        buildingId:'',
        unitId:'',
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      dialogFormVisible: false,
      showUnit: false,
      showRoom: false,
      buildingId: null,
      building: {
        buildingName: '',
        remark:''
      },
      unit:{
        unitName:'',
        buildingId:'',
        floor:null,
        elevator:true
      },
      room:{
        buildingId:'',
        unitId:'',
        floor:null,
        roomName:'',
        grossArea:'',
        usableArea:'',
        price:'',
        type:'',
        message:''
      },
      originalRoomName:'',
      roomNames:[],
      buildingList: [],
      unitList: [
        {
          id:'',
          label:''
        }
      ],
      roomList:[],
      pageInfo:[],
      selectBuilding: null,
      rules: {
        buildingName: [
          { required: true, message: "楼栋名不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback();
              }
              this.checkBuildingName(value, callback);
            }, trigger: "blur",
          },
        ],
        unitName: [
          {required:true,message:"单元名不能为空",trigger:"blur"},
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback();
              }
              this.checkUnitName(value, callback);
            }, trigger: "blur",
          }
        ],
        floor: [
          { required: true, message: "楼层不能为空", trigger: "blur" },
          {
            type: "number",
            min: 6,
            max: 26,
            message: "楼层数过低或过高,住宅楼层一般在6~26层之间",
            trigger: ["blur","change"] // 同时监听输入和失焦事件
          },
        ],
        elevator: [
          {
            required: true,
            message: '请选择是否有电梯',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (value === null || value === undefined) {
                callback(new Error('请选择是否有电梯'));
              } else {
                callback();
              }
            },
          },
        ],
        buildingId: [
          {required:true,message:'请在点击点击添加单元前先选择一栋楼',trigger:"change"},
        ],
        unitId: [
          {required:true,message:'请选择单元',trigger:"change"},
        ],
        roomName: [
          {required:true,message:"房间名不能为空",trigger:"blur"},
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback();
              }
              const floor = this.room.floor;

// 动态生成正则表达式
              const floorPart = floor >= 10 ? `([1-9]|[1-9]\\d|${floor})` : `[1-${floor}]`; // 处理楼层范围
              const roomNumberPart = `(0[1-9]|[1-9]\\d)`; // 房间号必须为两位数字（01~99）

// 完整正则：允许楼层号（1~floor） + 两位房间号（如 102、3001）
              const pattern = new RegExp(`^${floorPart}${roomNumberPart}$`);

              if (!pattern.test(value)) {
                callback(new Error('房间名格式应为：楼层号（1~30）+ 两位房间号（如102、3001）'));
              } else {
                // 进一步校验楼层号是否超过最大值（如 floor=30）
                const numFloor = parseInt(value.substring(0, value.length - 2), 10);
                if (numFloor > floor) {
                  callback(new Error(`楼层号不能超过${floor}`));
                } else if (this.originalRoomName !== value) {
                  this.checkRoomName(value, callback); // 确保 checkRoomName 正确处理回调
                } else {
                  callback();
                }
              }
            }, trigger: "blur",
          }
        ],
        grossArea:[
          {
            required: true,
            message: "房间面积不能为空",
            trigger: "blur"
          },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(); // 如果为空，前面已校验，这里直接返回
              }
              const numericValue = parseFloat(value);
              if (isNaN(numericValue) || numericValue <= 0) {
                callback(new Error('房间面积必须为大于0的数字'));
              } else {
                // 可添加更多复杂逻辑，例如面积范围限制
                if (numericValue > 500) {
                  callback(new Error('房间面积不能超过500平方米'));
                }
                else if (numericValue < 50) {
                  callback(new Error('不能低于50平方米'));
                }
                else {
                  // 可选：限制小数点后最多两位
                  const decimalPlaces = (value.toString().split('.')[1] || '').length;
                  if (decimalPlaces > 2) {
                    callback(new Error('房间面积最多保留两位小数'));
                  } else {
                    callback(); // 校验通过
                  }
                }
              }
            },
            trigger: "blur"
          }
        ],
        usableArea:[
          {
            required: true,
            message: "室内面积不能为空",
            trigger: "blur"
          },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback();
              }
              const numericValue = parseFloat(value);
              if (isNaN(numericValue) || numericValue <= 0) {
                callback(new Error('房间面积必须为大于0的数字'));
              }else {
                const grossArea = this.room.grossArea;
                if (numericValue > grossArea) {
                  callback(new Error('室内面积不能大于房间面积'));
                }
                else if(numericValue < 22){
                  callback(new Error('根据国家相关法律规定,室内面积必须在22平米以上'));
                }
                else {
                  // 可选：限制小数点后最多两位
                  const decimalPlaces = (value.toString().split('.')[1] || '').length;
                  if (decimalPlaces > 2) {
                    callback(new Error('室内面积最多保留两位小数'));
                  } else {
                    callback(); // 校验通过
                  }
                }
              }
            }
          }
        ],
        price: [
          { required: true, message: '物业费单价不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              // 去掉首尾空格（如果需要）
              const trimmedValue = String(value).trim();

              // 检查是否为空（避免用户输入全是空格的情况）
              if (trimmedValue === '') {
                return callback(new Error('物业费单价不能为空'));
              }

              // 转换为数字并检查是否是有效数字
              const numericValue = parseFloat(trimmedValue);
              if (isNaN(numericValue)) {
                return callback(new Error('物业费单价必须是数字'));
              }

              // 检查范围和小数位
              if (numericValue < 0) {
                callback(new Error('物业费单价不能为负数'));
              } else if (numericValue > 8) {
                callback(new Error('物业费定价不能太过离谱,请遵守相关法律法规,建议低于8元/㎡'));
              } else if (!/^\d+(\.\d{1,2})?$/.test(trimmedValue)) {
                callback(new Error('物业费单价最多保留两位小数'));
              } else {
                callback(); // 验证通过
              }
            },
            trigger: 'blur'
          },
        ],
        type:[
          { required: true, message: '房屋状态不能为空', trigger: 'change' },
        ],
        message:[
          {required:true,message:'房屋户型不能为空',trigger:"blur"},
          {
            validator: (rule, value, callback) => {
              // 示例：校验户型是否符合常见的格式（如 "2室1厅1卫"）
              const validFormats = /^[1-9]\d*室[1-9]\d*厅[1-9]\d*卫?$/; // 简单正则校验格式
              if (value && !validFormats.test(value)) {
                callback(new Error('房屋户型格式不正确，例如："2室1厅1卫"'));
              } else {
                callback();
              }
            },
            trigger: "blur"
          },
          {
            validator: (rule, value, callback) => {
              // 示例：限制户型描述的最大长度（如不超过20个字符）
              if (value && value.length > 20) {
                callback(new Error('房屋户型描述过长，请限制在20个字符以内'));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      },
    };
  },
  created() {
    this.getAllBuildingList();
    this.getRooms(1);
  },
  methods: {
// 修复后的 handleClickDelete 方法
    async handleClickDelete() {
      try {
        if (!this.selectBuilding) {
          this.$message.warning('请先选择要删除的楼栋');
          return;
        }
        console.log(this.selectBuilding);
        // 显式等待数据加载完成
        await this.getRooms(1);

        // 检查业主（自动等待异步完成）
        const hasOwners = await this.checkBuildingOwners(this.selectBuilding);

        if (hasOwners) {
          this.$message.warning('存在有业主居住的房间，无法删除');
          return;
        }
        // 显示确认对话框
        await this.$confirm(`确定要删除所选楼栋【`+this.selectBuilding.label+`】？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        // 执行删除请求（带超时配置）
        await this.axios.get("/admin/room/deleteRoomByBuildingId",{
          params:{buildingId:this.selectBuilding.id}
        }, {
          timeout: 10000 // 10 秒超时
        });
        this.$message.success('删除成功');
        this.searchRoom = {};
        this.getAllBuildingList();
        this.getRooms(1);
      } catch (error) {
        if (error.code === 'ECONNABORTED') {
          this.$message.error('请求超时，请检查网络或联系管理员');
        } else {
          this.$message.warning('取消删除');
          this.searchRoom = {};
          this.getAllBuildingList();
          this.getRooms(1);
        }
        this.loading = false;
      }
    },

// 修复后的 checkBuildingOwners 方法
    checkBuildingOwners(buildingNode) {
      return new Promise(async (resolve, reject) => {
        try {
          // 1. 请求楼栋数据
          const response = await this.axios.get("/admin/room/"+buildingNode.id);

          // 2. 检查数据有效性
          const roomList = response.data.roomList;
          if (!Array.isArray(roomList)) {
            throw new Error('roomList 数据格式错误');
          }

          // 3. 检查业主状态
          let hasOwners = false;
          for (const room of roomList) {
            if (room.ownerId) {
              hasOwners = true;
              break;
            }
          }
          resolve(hasOwners);
        } catch (error) {
          console.error('检查业主失败:', error);
          this.$message.error(error.message || '检查业主数据失败');
          reject(error);
        }
      });
    },
    async handleUpdate(row) {
      this.showEdit = true;
      // 转换 unitId 为数字类型
      await this.ChangeBuilding(Number(row.buildingId)); // 同时转换 buildingId
      const unitId = Number(row.unitId);

      // 检查转换结果是否为有效数字
      if (isNaN(unitId)) {
        console.error("unitId 不是有效数字:", row.unitId);
        return;
      }
      this.originalRoomName = row.roomName;
      this.room = {
        ...row,
        unitId: unitId // 赋值为数字类型
      };
    },
    handleDelete(row) {
      // 校验业主是否存在
      if (row.owner && row.owner.username) {
        this.$message.warning('请不要随便动迁有业主的房屋');
        return;
      }

      // 如果没有业主，继续删除流程
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除API
        this.axios.delete("admin/room/"+row.id).then(() => {
          this.$message.success('删除成功');
          this.getRooms(1);
        }).catch(err => {
          this.$message.error('删除失败: ' + err.message);
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    getRooms(pageNum){
      this.loading = true;
      this.axios.post("admin/room/list",this.searchRoom,{
        params:{pageNum:pageNum}
      })
          .then((res) => {
            this.pageInfo = res.data.pageInfo;
            this.loading = false;
            this.searchRoom = {};
          });
    },
    ChangeUnit(unitId){
      this.unit = '';
      this.axios.get("admin/unit/selectUnitById", {
        params: { id: unitId }
      }).then(response => {
        if (response.data.unit && typeof response.data.unit.floor === 'number') {
          this.room.floor = response.data.unit.floor;
          console.log('Updated floor:', this.room.floor); // 调试输出
        } else {
          console.error('Invalid floor value:', response.data.unit.floor);
          this.room.floor = null; // 设置一个合理的默认值
        }
      }).catch(error => {
        console.error('Failed to fetch unit data:', error);
        this.room.floor = null; // 设置一个合理的默认值
      });
    },
    ChangeBuilding(buildingId) {
      this.unitList = [];
      this.room.unitId = '';
      return new Promise((resolve, reject) => {
        this.axios.get("admin/unit/" + buildingId).then(res => {
          this.unitList = res.data.unitList;
          resolve();
        });
      });
    },
    getAllBuildingList() {
      this.axios.get("/admin/building/list").then(res => {
        this.buildingList = res.data.buildingList.map(building => ({
          id: building.id.toString(), // 强制转为字符串（如果后端返回 number）
          label: building.buildingName, // 确保 name 存在
          children: []
        }));
        this.$nextTick(() => {
          this.getAllUnit(); // 确保 buildingList 已更新
        });
      });
    },
    getAllUnit() {
      this.axios.get("admin/unit/list").then(res => {
        res.data.unitList.forEach(unit => {
          const building = this.buildingList.find(
              b => b.id === unit.buildingId.toString() // 确保类型一致
          );
          if (building) {
            if (!building.children) {
              this.$set(building, 'children', []);
            }
            if (!building.children.some(u => u.id === unit.id)) {
              building.children.push({
                id: unit.id,
                label: unit.unitName || `单元${unit.id}`
              });
            }
          } else {
            console.warn(`单元 ${unit.id} 的楼栋 ${unit.buildingId} 不存在！`);
          }
        });
      });

    },
    checkBuildingName(buildingName, callback) {
      buildingName = encodeURIComponent(buildingName);
      var url = "admin/building/" + buildingName;
      this.axios.get(url)
          .then((res) => {
            if (res.data.building) {
              callback(new Error("楼栋名已存在"));
            } else {
              callback();
            }
          })
          .catch(() => {
            callback(new Error("验证失败，请稍后重试"));
          });
    },
    checkUnitName(value, callback) {
      if (!this.unit.buildingId) {
        callback(new Error("未选择楼栋"));
        return;
      }
      var url = "admin/unit/selectUnitNameAndBuildingIdByUnit";
      this.axios.get(url,{
        params: {
          unitName:value,
          buildingId:this.unit.buildingId
        }
      })
          .then((res) => {
            if (res.data.unit) {
              callback(new Error("单元名已存在"));
            }else {
              callback();
            }
          })
          .catch(() => {
            callback(new Error("验证失败，请稍后重试"));
          });
    },
    checkRoomName(value, callback) {
      if (!this.room.buildingId){
        callback(new Error("未选择楼栋"));
        return;
      }
      if(!this.room.unitId){
        callback(new Error("未选择单元"));
        return;
      }
      this.axios.get("admin/room/selectRoomByBuildingIdAndUnitId",{
        params: {
          buildingId:this.room.buildingId,
          unitId:this.room.unitId,
          roomName:value
        }
      })
          .then((res) => {
            if (res.data.room) {
              callback(new Error("房间名已存在"));
            }else {
              callback();
            }
          })
          .catch(() => {
            callback(new Error("验证失败，请稍后重试"));
          });
    },
    handleAddBuilding() {
      this.dialogFormVisible = true;
      if (this.$refs.buildingForm) {
        this.$refs.buildingForm.resetFields();
      }
    },
    handleAddUnit() {
      if (!this.unit.buildingId){
        this.ChooseBuilding();
      }
      else {
        this.showUnit = true;
      }
    },
    handleAddRoom() {
      this.showRoom = true;
    },
    handleChooseBuilding(nodeData) {
      this.selectBuilding = nodeData;
      if (!nodeData?.id) {
        console.error('Invalid node data:', nodeData);
        return;
      }

      // 重置搜索条件
      this.searchRoom.unitId = '';
      this.searchRoom.buildingId = '';

      // 查找是否是子节点
      let isChildNode = false;
      for (const building of this.buildingList) {
        if (building.children?.some(child => child.id === nodeData.id)) {
          isChildNode = true;
          this.unit.buildingId = building.id;  // 赋值为父节点ID
          this.buildingId = building.id;
          this.searchRoom.unitId = nodeData.id;
          this.searchRoom.buildingId = building.id;
          break;
        }
      }

      // 如果是顶层节点
      if (!isChildNode) {
        this.unit.buildingId = nodeData.id;
        this.buildingId = nodeData.id;
        this.searchRoom.buildingId = nodeData.id;
      }
      this.getRooms(1);
    },
    handleRoomRemove() {
      this.showRoom = false;
      this.$refs.roomForm.resetFields();
      this.getRooms(1);
    },
    handleRoomSubmit() {
      this.$refs.roomForm.validate((valid) => {
        if (valid) {
          var roomName = this.room.roomName.trim();
          if(!roomName){
            this.$message.error("请输入房间名");
            return;
          }

          let floor = null;
          let roomNumber = null;
          if (roomName.length === 3) {
            // 格式如 "101" → 1 楼 01 号
            floor = parseInt(roomName[0], 10);
            roomNumber = parseInt(roomName.slice(1), 10);
          } else if (roomName.length === 4) {
            // 格式如 "1001" → 10 楼 01 号
            floor = parseInt(roomName.slice(0, 2), 10);
            roomNumber = parseInt(roomName.slice(2), 10);
          } else {
            this.$message.error('房间号格式错误，请输入 3 位或 4 位数字（如 101 或 1001）');
            return;
          }
          // 生成房间号列表（如 101, 201, ..., 1801）
          const generatedRooms = [];
          for (let f = floor; f <= this.room.floor; f++) {
            const roomCode = `${f}${String(roomNumber).padStart(2, '0')}`;
            generatedRooms.push({
              ...this.room,          // 复制基础数据
              roomName: roomCode,    // 覆盖房间名
              floor: f               // 动态设置实际楼层
            });
          }
          console.log(generatedRooms);
          // 添加到系统
          this.roomNames = [...this.roomNames, ...generatedRooms];
          this.axios.post("/admin/room/insert", generatedRooms)
              .then((res) => {
                console.log(res.data);
                this.showRoom = false;
                if (res.data.code === 200) {
                  this.AddSuccess();
                }
                else {
                  this.$message.error(res.data.data);
                }
                this.$refs.roomForm.resetFields();
                this.getRooms(1);
              });
        }
      });
    },
    handleRoomEditRemove() {
      this.showEdit = false;
      this.$refs.roomEditForm.resetFields();
    },
    handleRoomEditSubmit() {
      console.log(this.originalRoomName);
      this.$refs.roomEditForm.validate((valid) => {
        if (valid) {
          this.axios.post("/admin/room/update", this.room)
              .then((res) => {
                  if (res.data.code === 200) {
                    this.$message.success("修改成功");
                    this.showEdit = false;
                    this.getRooms(1);
                    this.$refs.roomEditForm.resetFields();
                  }
                  else {
                    this.$message.error("修改失败");
                    this.showEdit = false;
                    this.getRooms(1);
                    this.$refs.roomEditForm.resetFields();
                  }
              });
        }
      });
    },
    handleUnitRemove() {
      this.showUnit = false;
      this.$refs.unitForm.resetFields();
      this.buildingId = null;
      this.unit.buildingId = null;
    },
    handleUnitSubmit() {
      this.$refs.unitForm.validate((valid) => {
        if (valid) {
          this.axios.post("/admin/unit/insert", this.unit)
              .then(res => {
                this.showUnit = false;
                this.$refs.unitForm.resetFields();
                this.buildingId = null;
                this.getAllUnit();
                if (res.data.code === 200) {
                  this.AddSuccess();
                }
                else {
                  this.$message.error(res.data.data);
                }
              });
        }
      });
    },
    handleBuildingRemove() {
      this.dialogFormVisible = false;
      this.$refs.buildingForm.resetFields();
    },
    handleBuildingSubmit() {
      this.$refs.buildingForm.validate((valid) => {
        if (valid) {
          this.axios.post("/admin/building/insert", this.building)
              .then((res) => {
                this.dialogFormVisible = false;
                this.$refs.buildingForm.resetFields();
                if (res.data.code === 200) {
                  this.AddSuccess();
                }
                else {
                  this.$message.error(res.data.data);
                }
                this.getAllBuildingList(); // 重新获取数据以更新树
              });
        }
      });
    },
    ChooseBuilding() {
      this.$message({
        message:'请选择楼栋'
      });
    },
    AddSuccess() {
      this.$message({
        type: "success",
        message: '添加成功'
      });
    },
    handlePageNumChange(pageNum) {
      this.getRooms(pageNum);
    }
  },
};
</script>

<style>
.name{
  width: 140px;
  background: #cccccc;
  text-align: center;
}
.selected-node {
  background-color: #409eff !important; /* 选中背景色 */
  color: white !important; /* 选中字体颜色 */
  font-weight: bold;
}
.custom-form {
  display: flex;
  flex-direction: column;
}

.form-row {
  display: flex;
  gap: 16px; /* 控制两个输入框之间的间距 */
  margin-bottom: 16px; /* 控制每行之间的间距 */
}

.form-item {
  flex: 1; /* 每个输入框占相等的宽度 */
}

.full-width-item {
  flex: 2; /* 如果是单独一行，可以调整为需要的宽度比例，这里设置为 2 或 1 都可以 */
  width: 100%; /* 确保独占一行 */
}
</style>